
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from jwt import exceptions
import jwt
from django.conf import settings

class JwtQueryParamsAuth(BaseAuthentication):
    def authenticate(self, request):
        ## 检验请求里的 params 参数（这样会重写掉原来的请求参数，所以没用这种）
        # token = request.query_params.get('token')
        ## 检验请求里的头部 header 参数，这样不会重写其它参数，所以用这种
        token = request.META.get("HTTP_TOKEN")
        salt = settings.SECRET_KEY
        payload = None
        message = None
        try:
            payload = jwt.decode(jwt=token, key=salt, algorithms=['HS256'])
            # print(payload)
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({"success": False, "msg": "token已失效"})
        except jwt.DecodeError:
            raise AuthenticationFailed({"success": False, "msg": "token认证失败"})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({"success": False, "msg": "非法token"})
        return payload, token